﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Hyt.Core.Security;

namespace Hyt.Web
{
    public class CookiePassportManager
    {
        public string CookieName = "HYTPASSPORTKEY";
        public IPrincipalResolver PrincipalResolver { get; set; }
        public List<IPrincipal> GetPrincipals(HttpContext context)
        {
            string key = HttpHelper.GetCookie(context, CookieName);
            if (string.IsNullOrWhiteSpace(key))
            {
                return new List<IPrincipal>() {Principal.Anonymous};
            }
            try
            {
                key = Hyt.Core.Cryptography.DES.Decrypt(key);
            }
            catch (Exception)
            {
                return new List<IPrincipal>() { Principal.Anonymous };
            }
            string[] keys = key.Split(',');
            var result=new List<IPrincipal>();
            foreach (var str in keys)
            {
                var principal = PrincipalResolver.GetPrincipal(str);
                if (principal != null)
                {
                    result.Add(principal);
                }
            }
            return result.Any() ? result : new List<IPrincipal>() { Principal.Anonymous };
        }

        public void SavePrincipal(HttpContext context, IPrincipal principal)
        {
            string cookievalue = HttpHelper.GetCookie(context, CookieName);
            string key = principal.GetFullId(PrincipalResolver);
            var keys = new List<string>() { key };
            if (!string.IsNullOrWhiteSpace(cookievalue))
            {
                try
                {
                    key = Hyt.Core.Cryptography.DES.Decrypt(key);
                    keys.AddRange(key.Split(',').ToList());
                }
                catch (Exception)
                {
                    
                }
            }
            keys=keys.Distinct().ToList();
            string fullstr = Hyt.Core.Cryptography.DES.Encrypt(string.Join(",", keys));
            HttpHelper.WriteCookie(context, CookieName, fullstr);
        }

        public void Clear<T>(HttpContext context) where T : IPrincipal,new()
        {
            HttpHelper.WriteCookie(context, CookieName, "");
        }
    }

    public class CookiePassportManager<T> : CookiePassportManager
    {
        public IPrincipal GetPrincipal<T>(HttpContext context)
        {
            List<IPrincipal> principals = this.GetPrincipals(context);
            var principal = principals.FirstOrDefault(t => t is T);
            if (principal != null) return principal;
            return Principal.Anonymous;
        }
    }
}
